package com.servlet;

import com.model.Page;
import com.model.Post;
import com.service.PostService;
import com.service.PostServiceImpl;
import com.util.Constant;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/postList")
public class PostListServlet extends HttpServlet {
    private PostService postService = new PostServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNum = 1;
        try {
            pageNum = Integer.parseInt(req.getParameter("pageNum"));
        } catch (NumberFormatException e) { /* 默认第一页 */ }
        
        int pageSize = Constant.PAGE_SIZE;
        Integer categoryId = null;
        if (req.getParameter("categoryId") != null && !req.getParameter("categoryId").isEmpty()) {
            categoryId = Integer.parseInt(req.getParameter("categoryId"));
        }
        String keyword = req.getParameter("keyword");

        Page<Post> page = postService.getPostPage(pageNum, pageSize, categoryId, keyword);
		req.setAttribute("page", page);
		req.setAttribute("categoryId", categoryId);
		req.setAttribute("keyword", keyword);
		req.getRequestDispatcher("/index.jsp").forward(req, resp);
    }
}